package com.easybuy.controller;

import com.easybuy.Tools.MemcachedJava;
import com.easybuy.Tools.Page;
import com.easybuy.Tools.Wares;
import com.easybuy.pojo.Order;
import com.easybuy.pojo.UserAddress;
import com.easybuy.service.OrderService.OrderService;
import com.easybuy.service.UserAddressService.UserAddressService;
import com.easybuy.service.UserService.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;


@Controller
public class OrderController {
    @Autowired
    OrderService orderService;
    @Autowired
    UserService userService;
    @Autowired
    UserAddressService userAddressService;

    @RequestMapping("/getOrder")
    @ResponseBody
    public Page getOrder(@RequestParam(required = false) String condition,@RequestParam(required = false) Integer id,@RequestBody Page page){
        Map map=new HashMap();
        map.put("id",id);
        map.put("condition",condition);
        map.put("page",page);
        page=orderService.getOrder(map);
        return page;
    }
    @RequestMapping("/addOrder")
    @ResponseBody
    public String addOrder(@RequestParam String userId,@RequestParam int addressId,@RequestParam Double zongjia){
        Map userMap= (Map) MemcachedJava.getMcc().get(userId);
        List<Wares> shopList=(List) userMap.get("shopList");
        String loginName=userService.getUser(Integer.parseInt(userId)).getLoginName();
        UserAddress userAddress=userAddressService.getUserAddressById(addressId);
        Order order=new Order();
        order.setUserId(Integer.parseInt(userId));
        order.setLoginName(loginName);
        order.setCreateTime(new Date());
        order.setCost(zongjia);
        order.setUserAddress(userAddress.getAddress());
        order.setSerialNumber(UUID.randomUUID().toString());
        Map orderMap=orderService.addOrder(order);
        if (orderMap!=null){
            Integer orderId=(Integer)orderMap.get("orderId");
            for (Wares wares:shopList){
                wares.setOrderId(orderId);
                if (orderService.addOrderProduct(wares)<1){
                    return null;
                }

            }
        }else return null;
        shopList.clear();
        userMap.put("shopList",shopList);
        MemcachedJava.getMcc().set(userId,900,userMap);//清空购物车
        return order.getSerialNumber();
    }
}
